<template>
  <div>
    <button @click="createGold(5)">Create Gold</button>
    <div ref="goldLabel" class="gold-label">Gold: {{ goldCount }}</div>
    <div class="gold-container" ref="goldContainer">
      <div v-for="(gold, index) in golds" :key="index" class="gold"
        :style="{ left: gold.x + 'px', top: gold.y + 'px', opacity: gold.opacity, transform: `scale(${gold.scale})` }">
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      goldCount: 0,
      golds: [],
    };
  },
  methods: {
    createGold(num) {
      const goldLabelPosition = this.$refs.goldLabel.getBoundingClientRect();
      console.log(goldLabelPosition);

      for (let i = 0; i < num; i++) {
        const randomX = Math.random() > 0.5 ? Math.random() * 100 : -Math.random() * 100;
        const randomY = Math.random() > 0.5 ? Math.random() * 100 : -Math.random() * 100;
        this.golds.push({ x: randomX, y: randomY, scale: 1, opacity: 1 });
      }

      this.$nextTick(() => {
        this.golds.forEach((gold, index) => {
          const goldElement = this.$refs.goldContainer.children[index];
          this.animateGold(goldElement, goldLabelPosition);
        });
        this.updateGold(num);
      });
    },
    animateGold(goldElement, goldLabelPosition) {
      const vm = this;
      const animation = this.$refs.goldContainer.animate(
        [
          {
            transform: `translate(${goldElement.style.right}, ${goldElement.style.top}) scale(1)`,
            opacity: 1,
          },
          {
            transform: `translate(${goldLabelPosition.right}px, ${goldLabelPosition.top}px) scale(0.5)`,
            opacity: 0,
          },
        ],
        {
          duration: 1000,
          iterations: 1,
          easing: 'ease-in-out',
          fill: 'forwards',
        }
      );
      animation.onfinish = () => {
        // 移除元素
        goldElement.remove();
        // 更新 golds 数组
        const index = this.golds.findIndex(
          (gold) =>
            gold.x === parseFloat(goldElement.style.left) &&
            gold.y === parseFloat(goldElement.style.top)
        );
        if (index !== -1) {
          this.golds.splice(index, 1);
        }
      };
    },
    updateGold(num) {
      this.goldCount += num;
    },
  },
};
</script>

<style scoped>
.gold-label {
  position: absolute;
  top: 10px;
  left: 10px;
  color: black;
}

.gold-container {
  position: relative;
}

.gold {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: gold;
  border-radius: 50%;
}
</style>